<?php
/**
 * ============================================================================
 * * COPYRIGHT 2016-2019 xhadmin.com , and all rights reserved.
 * * WEBSITE: http://www.xhadmin.com;
 * ----------------------------------------------------------------------------
 * This is not a free software!You have not used for commercial purposes in the
 * premise of the program code to modify and use; and publication does not allow
 * any form of code for any purpose.
 * ============================================================================
 * Author: 寒塘冷月 QQ：274363574
 */
 

namespace app\admin\service;
use app\admin\service\FieldSetService;
use think\facade\Validate;
use think\exception\ValidateException;

class FormDataService
{
	
	//获取表单列表
	public static function getTableList($fieldList){
		$htmlstr .="	CodeGoods.initColumn = function () {\n";
		$htmlstr .=" 		return [\n";
		$htmlstr .=" 			{field: 'selectItem', checkbox: true},\n";
		$htmlstr .=" 			{title: '编号', field: 'data_id', visible: true, align: 'left', valign: 'middle'},\n";
		foreach($fieldList as $k=>$v){
			if(in_array($v['type'],[1,2,3,13])){
				if(!empty($v['config'])){
					$htmlstr .=" 			{title: '".$v['name']."', field: '".$v['field']."', visible: true, align: '".$v['align']."', valign: 'middle',formatter: 'CodeGoods.".$v['field']."Formatter'},\n";
				}else{
					$htmlstr .=" 			{title: '".$v['name']."', field: '".$v['field']."', visible: true, align: '".$v['align']."', valign: 'middle'},\n";
				}
			}else if(in_array($v['type'],[7,8,10,12])){
				$htmlstr .=" 			{title: '".$v['name']."', field: '".$v['field']."', visible: true, align: '".$v['align']."', valign: 'middle',formatter: 'CodeGoods.".$v['field']."Formatter'},\n";
			}else{
				$htmlstr .=" 			{title: '".$v['name']."', field: '".$v['field']."', visible: true, align: '".$v['align']."', valign: 'middle'},\n";
			}	
		}
		
		$htmlstr .=" 			{title: '操作', field: 'data_id', visible: true, align: 'center', valign: 'middle',formatter: 'CodeGoods.buttonFormatter'},,\n";
		
		$htmlstr .=" 		];\n";
		$htmlstr .=" 	};\n\n";
		
		
		foreach($fieldList as $key=>$val){
			
			if(!empty($val['config']) && ($val['type'] == 1 || $val['type'] == 13)){
				$htmlstr .="	CodeGoods.".$val['field']."Formatter = function(value,row,index) {\n";
				$htmlstr .="		if(value){\n";
				$htmlstr .="			return '<span class=\"label label-".$val['config']."\">'+value+'</span>';\n";
				$htmlstr .="		}\n";
				$htmlstr .="	}\n\n";
			}
			
			//格式化单选框 下拉框
			if($val['type'] == 2 || $val['type'] == 3){
				if(!empty($val['config'])){
					
					$htmlstr .="	CodeGoods.".$val['field']."Formatter = function(value,row,index) {\n";
					$htmlstr .="		if(value !== null){\n";
					$htmlstr .="			var value = value.toString();\n";
					$htmlstr .="			switch(value){\n";
					$data = explode(',',$val['config']);
					if($data && count($data) > 1){
						foreach($data as $key=>$val){
							$valArr = explode('|',$val);
							if($valArr){
								$htmlstr .="				case '".$valArr[1]."':\n";
								if(!empty($valArr[2])){
									$htmlstr .="					return '<span class=\"label label-".trim($valArr[2])."\">".$valArr[0]."</span>';\n";
								}else{
									$htmlstr .="					return '".$valArr[0]."';\n";
								}
								$htmlstr .="				break;\n";
							}
							
						}
					}
					
					$htmlstr .="			}\n";
					$htmlstr .="		}\n";
					$htmlstr .="	}\n\n";
				}
			}
			
			//格式化显示图片
			if($val['type'] == 8){
				$htmlstr .="	CodeGoods.".$val['field']."Formatter = function(value,row,index) {\n";
				$htmlstr .="		if(value){\n";
				$htmlstr .="			return \"<a href=\\\"javascript:void(0)\\\" onclick=\\\"openImg('\"+value+\"')\\\"><img height='30' src=\"+value+\"></a>\";	\n";
				$htmlstr .="		}\n";
				$htmlstr .="	}\n\n";
			}
			
			//附件下载
			if($val['type'] == 10){
				$htmlstr .="	CodeGoods.".$val['field']."Formatter = function(value,row,index) {\n";
				$htmlstr .="		if(value){\n";
				$htmlstr .="			return \"<a href=\"+value+\" target='_blank'>下载附件</a>\";	\n";
				$htmlstr .="		}\n";
				$htmlstr .="	}\n\n";
			}
			
			//格式化时间
			if($val['type'] == 7 || $val['type'] == 12){
				$htmlstr .="	CodeGoods.".$val['field']."Formatter = function(value,row,index) {\n";
				$htmlstr .="		if(value){\n";
				$htmlstr .="			return formatDateTime(value,'Y-m-d H:i:s');	\n";
				$htmlstr .="		}\n";
				$htmlstr .="	}\n\n";
			}
		}
		
		return $htmlstr;
	}
	
	//搜索加载
	public function getSearchGroup($searchlist){
		
		foreach($searchlist as $k=>$v){
			if(in_array($v['type'],[1,2,3,12,17])){
				if($v['type'] == 12){
					$htmlstr .= "							<div class=\"col-sm-3\">\n";
					$htmlstr .= "								<div class=\"input-group\">\n";
					$htmlstr .= "									<div class=\"input-group-btn\">\n";
					$htmlstr .= "										<button data-toggle=\"dropdown\" class=\"btn btn-white dropdown-toggle\" type=\"button\">".$v['name']."范围</button>\n";
					$htmlstr .= "									</div>\n";
					$htmlstr .= "									<input type=\"text\" autocomplete=\"off\" placeholder=\"时间范围\" class=\"form-control\" id=\"".$v['field']."\">\n";
					$htmlstr .= "								</div>\n";
					$htmlstr .= "							</div>\n";	
				}else{
					$htmlstr .= "							<div class=\"col-sm-2\">\n";
					$htmlstr .= "								<div class=\"input-group\">\n";
					$htmlstr .= "									<div class=\"input-group-btn\">\n";
					$htmlstr .= "										<button data-toggle=\"dropdown\" class=\"btn btn-white dropdown-toggle\" type=\"button\">".$v['name']."</button>\n";
					$htmlstr .= "									</div>\n";
					
					if($v['type'] == 1){
						$htmlstr .= "									<input type=\"text\" autocomplete=\"off\"   class=\"form-control\" id=\"".$v['field']."\" placeholder=\"".$v['name']."\" />\n";
					}
					
					if($v['type'] == 2 || $v['type'] == 3){
						$htmlstr .= "									<select class=\"form-control\" id=\"".$v['field']."\">\n";
						$htmlstr .= "										<option value=\"\">请选择</option>\n";
						
						$searchArr = explode(',',$v['config']);
						if($searchArr){
							foreach($searchArr as $k=>$v){
								$valArr = explode('|',$v);
								$htmlstr .= "										<option value=\"".$valArr[1]."\">".$valArr[0]."</option>\n";
							}
						}
						
						$htmlstr .= "									</select>\n";
					}
					$htmlstr .= "								</div>\n";
					$htmlstr .= "							</div>\n";	
				}
			}	
		}
		
		if($searchlist){
			$htmlstr .= "							<div class=\"col-sm-2\">\n";
			$htmlstr .= "									<button type=\"button\" class=\"btn btn-success \" onclick=\"CodeGoods.search()\" id=\"\">\n";
			$htmlstr .= "										<i class=\"fa fa-search\"></i>&nbsp;搜索\n";
			$htmlstr .= "									</button>\n";
			$htmlstr .= "							</div>\n";
		}
		return $htmlstr;
	}
	
	
	public static function getQueryParam($searchList){
		$htmlstr .="	CodeGoods.formParams = function() {\n";
		$htmlstr .="		var queryData = {};\n";
		
		foreach($searchList as $k=>$v){
			switch($v['type']){
				//时间段搜素
				case 12:
					$htmlstr .="		queryData['".$v['field']."_start'] = $('#".$v['field']."').val().split(\" - \")[0];\n";
					$htmlstr .="		queryData['".$v['field']."_end'] = $('#".$v['field']."').val().split(\" - \")[1];\n";
				break;
				
				default:
					$htmlstr .="		queryData['".$v['field']."'] = $(\"#".$v['field']."\").val();\n";	
				
			}
		}
		
		$htmlstr .="		return queryData;\n";
		$htmlstr .="	}\n\n";
		
		return $htmlstr;
	}
	
	//加载数据列表
	public static function loadList($where,$field,$limit,$orderby,$page,$extend_id){
		try{
			$extendInfo = db('extend')->where('extend_id',$extend_id)->find();
			if(!$extendInfo) throw new \Exception('没有模型信息');
			foreach( $where as $k=>$v){   
				if( !$v )   
					unset( $where[$k] );   
			}
			$res = db($extendInfo['table_name'])->where($where)->field($field)->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page]);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}	
		return ['rows'=>$res->items(),'total'=>$res->total()];		
	}
	

	
	//添加或者编辑数据
	public static function saveData($type,$data,$fieldList){
		$extendInfo = db('extend')->where('extend_id',$data['extend_id'])->find();
		if(!$extendInfo){
			throw new ValidateException('没有模型信息');
		}
		$rules = [];
		$msg = [];
		foreach($fieldList as $key=>$v){		
			$rule = [];
			if(!empty($v['validate']) || !empty($v['rule'])){
				if(in_array('notEmpty',explode(',',$v['validate']))){
					array_push($rule,'require');
					$msg[$v['field'].'.require'] = $v['name'].'不能为空';
				}

				if(in_array('unique',explode(',',$v['validate']))){
					array_push($rule,'unique:'.config('my.create_table_pre').$extendInfo['table_name']);
					$msg[$v['field'].'.unique'] = $v['name'].'已存在';
				}
				
				if(!empty($v['rule'])){
					$rule['regex'] = html_out($v['rule']);
					$msg[$v['field'].'.regex'] = $v['name'].'格式错误';
				}
				$rules[$v['field']] = $rule;
			}
		}
		
		$validate = Validate::rule($rules)->message($msg);	
		if (!$validate->check($data)) {
			throw new ValidateException($validate->getError());
		}
		try{
			if($type == 'add'){
				foreach($fieldList as $k=>$v){
					if($v['type'] == 7){
						$data[$v['field']] = strtotime($data[$v['field']]);
					}
					if($v['type'] == 12){
						$data[$v['field']] = time();
					}
					if($v['type'] == 20){
						$data[$v['field']] = ip();
					}
				}
				$reset = db($extendInfo['table_name'])->insert($data);
			}elseif($type == 'edit'){
				foreach($fieldList as $k=>$v){
					if($v['type'] == 7){
						$data[$v['field']] = strtotime($data[$v['field']]);
					}
				}
				$reset = db($extendInfo['table_name'])->update($data);				
			}
		}catch(\Exception $e){
			abort(config('my.error_log_code'),$e->getMessage());
		}	
		return $reset;
	}
	
	
	//批量删除
	public static function delete($where,$extend_id){
		try{		
			$extendInfo = db('extend')->where('extend_id',$extend_id)->find();
			if(!$extendInfo){
				throw new ValidateException('没有模型信息');
			}
			$reset = db($extendInfo['table_name'])->where($where)->delete();
		}catch(\Exception $e){
			abort(config('my.error_log_code'),$e->getMessage());
		}	
		return $reset;	
	}
	
	
}
